import React, { useEffect, useState } from "react";
import { Button, message, Table, Modal, Radio,Input } from "antd";
import { articleColumn } from "./column";
import { useDispatch, useSelector } from "react-redux";
import SearchPart from "./components/ArticleSearch";
import { getArticles } from "@/store/slices/articleSlice.js";
import ArticleDialog from "./components/articleDialog";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import articleStyle from "./article.module.scss";
import { deleteArticle, modifyArticle, deleteArticles,addClawUrl } from "@/api/article.js";
import { getCommonList } from "@/api/index.js";

export default function Article() {
  const { articleList, total, currentPage, pageSize } = useSelector(
    (state) => state.article
  );
  const [selectIds, setSelectIds] = useState([]);
  const [cateEnumList, setCateEnumList] = useState([]);
  const [tagEnumList, setTagEnumList] = useState([]);
  const [pagination, setPagination] = useState({
    current: currentPage,
    pageSize,
  });
  const [dialogType, setDialogType] = useState(0); //默认0为添加，1为编辑
  const [articleDialogVisible, setVisible] = useState(false);
  const [id, setId] = useState();
  const [clawDialog, setClawDialogVisible] = useState(false);
  const [clawUrl,setClawUrl] = useState("");
  const dispatch = useDispatch();
  useEffect(() => {
    getList();
    getCommonType();
  }, [pagination.current, pagination.pageSize]);

  const handleDialogTypeAndId = (id) => {
    setDialogType(1);
    setId(id);
  };

  const handleDialog = (flag, params) => {
    setVisible(flag);
    if (params && params.type) {
      getList();
    }
  };
  const getList = () => {
    dispatch(
      getArticles({
        page: pagination.current,
        size: pagination.pageSize,
      })
    );
  };

  const getCommonType = async () => {
    const res = await getCommonList({ type: "cate-type" });
    setCateEnumList(res.data);
    console.log(res, "@@@");
    const res2 = await getCommonList({ type: "tag-type" });
    console.log(res2, "$$$");
    setTagEnumList(res2.data);
  };

  const handleDeleteArticle = async (id) => {
    console.log(id, "获取到的id");
    try {
      const res = await deleteArticle(id);
      console.log("res", res);
      message.success(res.message);
    } catch (e) {
      message.error("删除失败！");
    }
    getList();
  };

  // 批量删除
  const handleDeleteArticles = async () => {
    const res = await deleteArticles({ ids: selectIds });
    console.log(selectIds, "@@@");
    if (res.code === 200) {
      message.success("删除成功");
    }
    getList();
  };

  // 当前页发生变化
  const handlePageChange = (page, _) => {
    setPagination((pre) => ({ ...pre, current: page }));
    console.log(page);
  };
  // pagesize发生变化
  const handleSizeChange = (_, size) => {
    console.log(size);
    setPagination((pre) => ({ ...pre, pageSize: size }));
  };
  // switch修改
  const handleChangeIsTop = async (id, checked) => {
    const res = await modifyArticle({ id, isTop: checked });
    console.log("switch修改", res);
    getList();
  };
  //多选
  const handleRowSelect = (selectedRowKeys) => {
    console.log(selectedRowKeys, "select");
    setSelectIds(selectedRowKeys);
  };

  const columns = articleColumn({
    setVisible,
    handleDialogTypeAndId,
    deleteById: handleDeleteArticle,
    handleChangeIsTop,
  });

  //begin 文章抓取部分
  const handleOpenClaw = () => {
    setClawDialogVisible((pre) => !pre);
  };

  const handleCloseClaw = () => {
    setClawDialogVisible(false);
  };

  const handleClawUrl = (e)=>{
      setClawUrl(e.target.value);
  }

  const handleClawOk = async ()=>{
    const res = await addClawUrl({url:clawUrl});
    setClawDialogVisible(false);
    getList();
  }
  // end

  return (
    <div className={articleStyle.article}>
      <Modal
        title="文章抓取"
        open={clawDialog}
        onOk={handleClawOk}
        onCancel={handleCloseClaw}
        cancelText="取消"
        okText="确定"
      >
        <div className={articleStyle['form-item']}>
          <span className="label" style={{marginRight:'10px',minWidth:"100px"}}>抓取类型</span>
          <Radio.Group defaultValue={1}>
            <Radio value={1}>CSDN</Radio>
            <Radio value={2} disabled>禁用</Radio>
          </Radio.Group>
        </div>
        <div className={articleStyle['form-item']}>
          <span className="label" style={{marginRight:'10px',minWidth:"100px"}}>目标地址url</span>
          <Input value={clawUrl} onChange={handleClawUrl}></Input>
        </div>
      </Modal>
      <div className={articleStyle.top}>
        <SearchPart
          cateEnumList={cateEnumList}
          tagEnumList={tagEnumList}
        ></SearchPart>
        <div className="actionBtn" style={{ marginBottom: "10px" }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            style={{ marginRight: "10px", padding: "2px 10px" }}
            onClick={() => {
              setVisible(true);
              setDialogType(0);
            }}
          >
            添加
          </Button>
          <Button
            type="primary"
            danger
            icon={<DeleteOutlined />}
            onClick={handleDeleteArticles}
            style={{ marginRight: "10px", padding: "2px 5px" }}
          >
            批量删除
          </Button>
          <Button type="primary" onClick={handleOpenClaw}>
            文章抓取
          </Button>
        </div>
      </div>

      <ArticleDialog
        id={id}
        isopen={articleDialogVisible}
        setVisible={handleDialog}
        type={dialogType}
      ></ArticleDialog>

      <div className={articleStyle["table-container"]}>
        <Table
          rowSelection={{
            selections: selectIds,
            onChange: handleRowSelect,
          }}
          columns={columns}
          dataSource={articleList}
          rowKey="id"
          // scroll设置为x100%,这样设置列宽才生效（多列的情况下）
          scroll={{ x: "100%" }}
          pagination={{
            pageSize: pagination.pageSize,
            current: pagination.current,
            pageSizeOptions: [3, 5, 10, 20],
            showSizeChanger: true,
            total,
            showTotal: (total) => `共${total}条`,
            onChange: handlePageChange,
            onShowSizeChange: handleSizeChange,
          }}
        />
      </div>
    </div>
  );
}
